<!--
 * @Descripttion: 设备档案表单
 * @LastEditors: xzh
 * @LastEditTime: 2024-01-04 11:29:31
-->
<template>
  <DileDrawer
    v-model="equipArchivesForm.visible"
    :loading="equipArchivesForm.loading"
    size="80%"
    @sure="hanldeSure"
  >
    <template #header>
      <span>{{
        $t(`table.btnArr.${!equipArchivesForm.formData.id ? "add" : "edit"}`)
      }}</span>
    </template>
    <template #default>
      <el-form
        ref="formRef"
        class="el-form-card"
        :model="equipArchivesForm.formData"
        :rules="formRules"
        label-width="6.5rem"
        size="large"
        status-icon
      >
        <!-- 设备信息 -->
        <el-card>
          <template #header>
            <span>{{
              $t("page.equipManageArr.equipArchivesArr.equipInfo")
            }}</span>
          </template>

          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.code')"
            >
              <el-input
                v-model="equipArchivesForm.formData.code"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.name')"
              prop="name"
            >
              <el-input
                v-model="equipArchivesForm.formData.name"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.specification')"
            >
              <el-input
                v-model="equipArchivesForm.formData.specification"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipType')"
              prop="typeId"
              :validate-status="
                !!equipArchivesForm.formData.typeId ? 'success' : ''
              "
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="equipArchivesForm.formData.typeId"
                :selectType="selectTypeEnum.equipType"
                :cacheLabel="equipArchivesForm.formData.extJson.typeName"
                :expand-on-click-node="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.factory')"
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="equipArchivesForm.formData.factoryId"
                :expand-on-click-node="false"
                :cacheLabel="equipArchivesForm.formData.extJson.factoryName"
                :extraConditions="{
                  type: DepartTypeEnum.factory,
                }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.systemManageArr.position')">
              <el-select
                v-model="equipArchivesForm.formData.positionId"
                :placeholder="$t('common.select')"
              >
                <el-option
                  v-for="item in equipArchivesForm.resoure.positionArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.ownProcess')"
            >
              <el-select
                v-model="equipArchivesForm.formData.processId"
                :placeholder="$t('common.select')"
              >
                <el-option
                  v-for="item in equipArchivesForm.resoure.processDefineArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.systemManageArr.positionArr.customer')"
              prop="customerId"
              :validate-status="
                !!equipArchivesForm.formData.customerId ? 'success' : ''
              "
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="equipArchivesForm.formData.customerId"
                :selectType="selectTypeEnum.customer"
                :cacheLabel="equipArchivesForm.formData.extJson.customerName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="
                $t('page.equipManageArr.equipArchivesArr.dayStandardHour')
              "
            >
              <el-input-number
                v-model="equipArchivesForm.formData.dayStandardHour"
                controls-position="right"
                :min="0"
                :max="12"
                :precision="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="
                $t('page.equipManageArr.equipArchivesArr.nightStandardHour')
              "
            >
              <el-input-number
                v-model="equipArchivesForm.formData.nightStandardHour"
                controls-position="right"
                :min="0"
                :max="12"
                :precision="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('common.remark')">
              <el-input
                v-model="equipArchivesForm.formData.remark"
                :rows="5"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 使用情况 -->
        <el-card>
          <template #header>
            <span>{{ $t("page.equipManageArr.equipArchivesArr.usage") }}</span>
          </template>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.currentStatus')"
              prop="currentStatus"
            >
              <el-select
                v-model="equipArchivesForm.formData.currentStatus"
                :placeholder="$t('common.select')"
              >
                <el-option
                  v-for="item in equipArchivesForm.resoure.equipStateArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.department')"
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="equipArchivesForm.formData.departmentId"
                :expand-on-click-node="false"
                :cacheLabel="equipArchivesForm.formData.extJson.departmentName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.manager')"
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="equipArchivesForm.formData.manager"
                :selectType="selectTypeEnum.people"
                :cacheLabel="equipArchivesForm.formData.extJson.managerName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.contact')"
              prop="contact"
            >
              <el-input
                v-model="equipArchivesForm.formData.contact"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.activationTime')"
            >
              <el-date-picker
                v-model="equipArchivesForm.formData.activationTime"
                type="date"
                value-format="YYYY-MM-DD"
                :placeholder="$t('common.selectDate')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipManageArr.equipArchivesArr.totalRower')"
            >
              <el-input
                v-model="equipArchivesForm.formData.totalRower"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
        </el-card>
      </el-form>
    </template>
  </DileDrawer>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, nextTick, toRef } from "vue";
import type { object_Inf } from "@/utils/typings/index.type";
import { useI18n } from "vue-i18n";
import { ElNotification } from "element-plus";
import { selectTypeEnum } from "@/components/dile-selectItem/index.type";
import { DepartTypeEnum } from "@typings/organizeManage/index.type";
import DileInputSelectItem from "@/components/dile-selectItem/selectItem-input/index.vue";
import DileDrawer from "@/components/dile-drawer/index.vue";
import Dile_APi from "@/api";
import Dile_Methods from "@/utils/methods";

const emit = defineEmits(["refresh"]);

let { t } = useI18n();

/**
 * @Author: xzh
 * @Descripttion: 表单默认数据
 * @Param:
 */
let defaultData = () => ({
  id: 0,
  status: true, //状态
  //设备信息
  name: "", //设备档案名称
  code: "", //设备档案编码
  specification: "", //规格型号
  typeId: null, //设备类型
  factoryId: null, //所在工厂
  positionId: null, //存放位置
  processId: null, //所属制程
  customerId: null, //所属客户
  dayStandardHour: 0, //日班标准工时
  nightStandardHour: 0, //夜班标准工时
  remark: "", //备注
  //使用情况
  currentStatus: null, //当前状态
  departmentId: null, //使用部门
  manager: null, //负责人
  contact: "", //联系方式
  activationTime: null, //启用日期
  totalRower: "", //总功(kw)
  //购置信息
  // purchaseOrderId: null, //采购订单
  // supplier: null, //供应商
  // supplierName: "", //供应商名称
  // manufacturer: "", //生产厂商
  // purchaseDepartmentId: null, //采购部门
  // purchaseUserId: null, //采购人员
  // purchaseUserName: "", //采购人员名称
  // purchaseDate: null, //采购日期
  // productionDate: null, //出厂日期
  // serviceLife: 1, //使用寿命
  // price: 0, //购买价格
  extJson: {
    typeName: "", //设备类型名称
    factoryName: "", //所在工厂名称
    customerName: "", //所属客户名称
    departmentName: "", //使用部门名称
    managerName: "", //负责人名称
    // purchaseDepartmentName: "", //采购部门名称
    // purchaseUserName: "", //采购人员名称
  },
});
/**
 * @Author: xzh
 * @Descripttion: 设备档案表单参数
 * @Param:
 */
let equipArchivesForm = reactive<object_Inf>({
  visible: false,
  loading: false,
  //表单数据
  formData: defaultData(),
  resoure: {
    //设备状态
    equipStateArr: [],
    //存放位置
    positionArr: [],
    //工序定义
    processDefineArr: [],
  },
});

/**
 * @Author: xzh
 * @Descripttion: 表单实例
 * @Param:
 */
let formRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion:表单验证规则
 * @Param:
 * @param {*} computed
 */
let formRules = computed((): any => {
  return reactive({
    name: [
      {
        required: true,
        message:
          t("common.enter") + t("page.equipManageArr.equipArchivesArr.name"),
        trigger: "change",
      },
    ],
    typeId: [
      {
        required: true,
        message: t("common.select") + t("page.equipManageArr.equipType"),
        trigger: "change",
      },
    ],
    customerId: [
      {
        required: true,
        message:
          t("common.select") + t("page.systemManageArr.positionArr.customer"),
        trigger: "change",
      },
    ],
    currentStatus: [
      {
        required: true,
        message:
          t("common.select") +
          t("page.equipManageArr.equipArchivesArr.currentStatus"),
        trigger: "change",
      },
    ],
    contact: [
      {
        validator: (rule: any, value: any, callback: any) => {
          //验证手机号
          Dile_Methods.validator_phone(value) || !value
            ? callback()
            : callback(
                new Error(
                  t("common.message.pleaseEnterRight") +
                    t(`page.equipManageArr.equipArchivesArr.contact`)
                )
              );
        },
        trigger: "change",
      },
    ],
  });
});

/**
 * @Author: xzh
 * @Descripttion:初始化加载
 * @Param:
 * @param {*} id 设备档案主键
 */
let init = async (id: number) => {
  let { visible, loading } = toRefs(equipArchivesForm);
  visible.value = true;
  await nextTick();
  try {
    loading.value = true;
    //加载表单资源
    await initSearchResource();
    //加载表单数据
    await initFormData(id);
  } finally {
    loading.value = false;
  }
};

/**
 * @Author: xzh
 * @Descripttion: 加载表单数据
 * @Param:
 */
let initFormData = async (id: number) => {
  let data: object_Inf = !!id
    ? await Dile_APi.getEquipArchivesInfo(id)
    : defaultData();
  Object.assign(equipArchivesForm.formData, data);
};

/**
 * @Author: xzh
 * @Descripttion: 加载表单资源
 * @Param:
 */
let initSearchResource = async () => {
  //加载设备状态资源
  await initEquipStateResource();
  //加载存放位置
  await initPositionResource();
  //加载工序定义
  await initProcessDefineResource();
};

/**
 * @Author: xzh
 * @Descripttion: 加载设备状态资源
 * @Param:
 */
let initEquipStateResource = async () => {
  let equipStateArr = toRef(equipArchivesForm.resoure, "equipStateArr");
  //加载所有设备状态
  equipStateArr.value = Dile_Methods.filterDataArr(
    (await Dile_APi.getEquipStatePageList()).map((state: object_Inf) => ({
      value: state.id,
      label: state.name,
    }))
  );
};
/**
 * @Author: xzh
 * @Descripttion: 加载存放位置
 * @Param:
 */
let initPositionResource = async () => {
  let positionArr = toRef(equipArchivesForm.resoure, "positionArr");
  //加载所有存放位置
  positionArr.value = Dile_Methods.filterDataArr(
    (await Dile_APi.getPositionList()).map(({ id, position }: object_Inf) => ({
      value: id,
      label: position,
    }))
  );
};
/**
 * @Author: xzh
 * @Descripttion: 加载设备存放位置
 * @Param:
 */
let initProcessDefineResource = async () => {
  let processDefineArr = toRef(equipArchivesForm.resoure, "processDefineArr");
  //加载所有设备存放位置
  processDefineArr.value = Dile_Methods.filterDataArr(
    (await Dile_APi.getProcessDefineList()).map(({ id, name }: object_Inf) => ({
      value: id,
      label: name,
    }))
  );
};

/**
 * @Author: xzh
 * @Descripttion: 保存事件
 * @Param:
 */
let hanldeSure = async () => {
  let { formData, loading, visible } = toRefs(equipArchivesForm),
    valid = await formRef.value.validate();
  if (!valid || !!loading.value) {
    return false;
  }
  try {
    loading.value = true;
    await Dile_APi.saveEquipArchives(formData.value);
    //触发刷新回调
    emit("refresh");
    //提示成功
    ElNotification({
      message: t("common.message.OperationSuccess"),
      type: "success",
    });
    //关闭弹框
    visible.value = false;
  } finally {
    loading.value = false;
  }
};

defineExpose({
  init,
});
</script>
<style lang="scss" scoped></style>
